<template>
  <auth-page>
    <view
      class="business-district-index-page"
      :style="{ '--themeColor': themeColor }"
    >
      <nav-bar
        :bgColor="isFixed ? '#fff' : 'transparent'"
        :isPlaceholder="false"
        :supportWhiteBlack="isFixed ? false : true"
        ref="navBar"
        class="navBarClass"
      >
        <view slot="navLeft" class="navLeft">
          <u-search
            @click="
              $Router.push({
                name: 'businessDistrictShopSearch',
                params: {
                  pubShopId: pubShopId,
                },
              })
            "
            height="54rpx"
            placeholder="搜索商户"
            :disabled="true"
            :clearabled="false"
            :showAction="false"
          ></u-search>
        </view>
      </nav-bar>
      <view
        :class="['content', showCoupon ? 'disable-touch' : '']"
        :style="{
          minHeight: `calc(100vh + ${scrollHeight}px)`,
        }"
      >
        <view class="head-bg">
          <xh-img :src="shopInfo.images" />
        </view>
        <view class="container">
          <view class="head" v-if="shopInfo">
            <view class="head-content">
              <view class="top">
                <view class="top-left">
                  <view class="shopName">
                    <view
                      :class="['flag', shopInfo.allStatus === 0 ? 'open' : '']"
                    >
                      {{ shopInfo.allStatus === 0 ? "营业中" : "休息中" }}
                    </view>
                    <view
                      class="title title-Hidden-one"
                      @click="
                        handleMixinAuth($myTool.jumpPage, 'shopDetail', {
                          shopId: shopInfo.id,
                        })
                      "
                    >
                      {{ shopInfo.shopName || "" }}
                    </view>
                  </view>
                  <view class="address">
                    <view class="address title-Hidden-one"
                      >{{ shopInfo.provinceCode }}{{ shopInfo.cityCode
                      }}{{ shopInfo.areaCode }}{{ shopInfo.address }}</view
                    >
                  </view>
                </view>
                <view class="top-right">
                  <view
                    class="btn lookLocation"
                    @click="
                      handleMixinAuth(
                        $myTool.lookLocation,
                        shopInfo.latitude,
                        shopInfo.longitude,
                        shopInfo.shopName,
                        `${shopInfo.provinceCode}${shopInfo.cityCode}${shopInfo.areaCode}${shopInfo.address}`
                      )
                    "
                  >
                    <image
                      src="https://hyyxboss.oss-cn-shenzhen.aliyuncs.com/img/pub/look-location.png"
                      class="img-icon"
                    ></image>
                    <view class="title">导航</view>
                  </view>
                  <view
                    class="btn"
                    @click="handleMixinAuth($myTool.callPhone, shopInfo.phone)"
                  >
                    <image
                      src="https://hyyxboss.oss-cn-shenzhen.aliyuncs.com/img/pub/call-phone.png"
                      class="img-icon"
                    ></image>
                    <view class="title">电话</view>
                  </view>
                </view>
              </view>
              <view class="bottom">
                <view
                  class="ticket"
                  v-if="isShowCouponDown && couponList.length > 0 && couponList"
                >
                  <scroll-view class="ticket_list" scroll-x="true">
                    <ticket-item
                      v-for="(item, index) in couponList"
                      :key="index"
                      :denomination="item.denomination"
                      :discountPercent="item.discountPercent"
                      :transactionMinimum="item.transactionMinimum"
                      :receiveCode="item.receiveCode"
                    />
                  </scroll-view>
                  <view
                    class="see_all"
                    v-if="couponList && couponList.length >= 2"
                    @click="handleMixinAuth(showCouponList)"
                  >
                    更多<u-icon
                      name="arrow-right"
                      color="#999999"
                      size="26rpx"
                    />
                  </view>
                </view>
              </view>
            </view>
          </view>
          <view
            class="tabs"
            :class="[isFixed ? 'transition' : '']"
            :style="{
              position: isFixed ? 'fixed' : 'relative',
              top: isFixed ? navBarHeight + 'px' : '0',
              left: isFixed ? 0 : 0,
              zIndex: isFixed ? 100 : 0,
            }"
          >
            <u-tabs
              :list="classification"
              :lineColor="themeColor"
              :activeStyle="{ color: themeColor }"
              @click="handleChangeClassify"
            ></u-tabs>
          </view>
          <view
            class="shop-list"
            v-if="shopList.length > 0"
            :style="{
              marginTop: isFixed ? `calc(${tabsHeight}px + 16rpx)` : '16rpx',
            }"
          >
            <view class="list">
              <view
                v-for="item in shopList"
                :key="item.id"
                class="shop-content"
              >
                <view class="img">
                  <xh-img
                    :src="item.logo"
                    @click="
                      $myTool.jumpPage('shopIndex', {
                        shopId: item.id,
                      })
                    "
                  />
                </view>
                <view class="msg">
                  <view
                    class="top"
                    @click="
                      $myTool.jumpPage('shopIndex', {
                        shopId: item.id,
                      })
                    "
                  >
                    <view class="title">{{ item.name }}</view>
                    <view class="detail">
                      <view class="left">
                        <div class="type">
                          {{ industryType[item.industry] }}
                        </div>
                        <view class="month">月售{{ item.monthSales }}</view>
                      </view>
                      <view class="distance" v-if="item.distance">
                        {{ $myTool.transitionDistance(item.distance) }}
                      </view>
                    </view>
                  </view>

                  <view class="store-val coupons" v-if="item.pubCoupons">
                    <view class="ticket">
                      <scroll-view class="ticket_list" scroll-x="true">
                        <ticket-item
                          v-for="coupon in item.pubCoupons"
                          :key="coupon.id"
                          :denomination="coupon.denomination"
                          :discountPercent="coupon.discountPercent"
                          :transactionMinimum="coupon.transactionMinimum"
                          :receiveCode="coupon.receiveCode"
                        />
                      </scroll-view>
                      <view
                        class="see_all"
                        v-if="item.pubCoupons && item.pubCoupons.length >= 2"
                        @click="
                          $myTool.jumpPage('shopIndex', {
                            shopId: item.id,
                            showTicket: true,
                          })
                        "
                      >
                        更多<u-icon
                          name="arrow-right"
                          color="#999999"
                          size="26rpx"
                        />
                      </view>
                    </view>
                  </view>
                </view>
              </view>
            </view>
          </view>
          <view class="empty" v-else>
            <list-enpty
              iconUrl="https://hyyxboss.oss-cn-shenzhen.aliyuncs.com/img/pub/empty-nearby-business-district.png"
            />
          </view>
        </view>
        <view class="list list-placer" style="height: 50px"></view>
        <shop-coupon
          title="商圈优惠"
          :couponList="couponList"
          :visible.sync="showCoupon"
          @pullDownCoupon="pullDownCoupon"
        />
      </view>
      <view class="no_touch" @touchmove.stop.prevent v-if="showLoading">
        <view class="content">
          <view class="icon"><u-loading-icon></u-loading-icon></view>
          <view class="text">加载中...</view>
        </view>
      </view>
    </view>
  </auth-page>
</template>

<script>
import shopCoupon from "@/pages/sp-store/pages/shop-index/components/shopCoupon";
import {
  getShopDetail,
  userJoinPubDomainBusinessUser,
  getQrcodeScan,
  getShops,
} from "@/service/api/sp-store/index";
import { headImg, TABLE_QUERY_KEY } from "../../const";
import { mixinAuth } from "@/mixin/sp-common/mixin-auth";
import { mapState } from "vuex";
import { receiveCoupon, getCoupon } from "@/service/api/sp-coupon/index";
import { getUrlQuery } from "@/utils/format";
import { appSetStorage } from "@/utils/storage";
import ticketItem from "../../components/ticket-item";
import { getPubTagShopsByClassifyId } from "@/service/api/sp-store/businessDistrict";

export default {
  mixins: [mixinAuth],
  data() {
    return {
      classification: [
        // {
        //   name: "全部(80)",
        //   id: 0,
        // },
        // {
        //   name: "美食(10)",
        //   id: 0,
        // },
      ],
      tabActive: 0,
      shopInfo: null,
      pubShopId: "",
      pubDomainShopId: "",
      headImg: headImg,
      couponList: [],
      isShowCouponDown: true,
      showCoupon: false,
      showLoading: true,
      isHasChangeClassify: false,
      shopList: [],
      scrollHeight: 0,
      navBarHeight: 0,
      tabsHeight: 0,
      originScrollTop: 0,
      isFixed: false,
    };
  },
  computed: {
    ...mapState("sp-common/base", ["themeColor"]),
    ...mapState("sp-store/index", [
      "industryType",
      "cartData",
      "lowCompatibility",
    ]),
    ...mapState("sp-common/auth", ["app_token", "isAnonUser"]),
  },
  components: {
    shopCoupon,
    ticketItem,
  },
  created() {},
  mounted() {
    this.pubShopId = this.$Route?.query?.shopId;
    if (!this.app_token) return;
    this.initShop().then(() => {
      this.$nextTick(() => {
        if (
          this.$Route?.query?.showTicket &&
          this.$Route?.query?.showTicket === "true"
        ) {
          this.showCouponList();
        }
      });
    });
  },
  onReady() {},
  onShow() {
    this.innitQRCode();
  },
  onLoad(options) {
    console.log("商圈首页跳转参数", options);
  },
  watch: {
    app_token() {
      this.initShop();
      this.innitQRCode();
    },
  },
  onPageScroll(e) {
    this.handlePageScrollTo(e);
  },
  // 分享
  onShareAppMessage() {
    let {
      shopInfo: { shopName, logo, copywrite },
    } = this;
    return {
      title: copywrite ? copywrite : shopName,
      path: `pages/sp-store/pages/shop-index/index?shopId=${this.pubShopId}`,
      imageUrl: logo ? process.env.VUE_APP_BASE_FileUrl + logo : "",
      success: (res) => {
        console.info(res);
      },
    };
  },
  methods: {
    innitQRCode() {
      if (this.$Route?.query?.q) {
        //来自桌码
        const options = this.$Route?.query;
        //q=https%253A%252F%252Fcloudtest.xiangsaopay.com%252Fqr%253Ftype%253Dorder%2526deptId%253D1123598813738675201%2526code%253DFHB1230000000009&scancode_time=1679380269
        const q = decodeURIComponent(options?.q);
        const query = getUrlQuery(q);
        this.fetchQRCodeDetail(query);
      }
    },
    async fetchQRCodeDetail(query) {
      const res = await getQrcodeScan({ deviceNo: query.code });
      if (res) {
        this.pubDomainShopId = res?.bizData?.pubDomainShopId;
        this.pubShopId = res?.bizData?.pubDomainShopId;
        appSetStorage(TABLE_QUERY_KEY, JSON.stringify(res?.bizData));
        console.log("桌码参数", res?.bizData);
        this.$nextTick(() => {
          this.initShop();
        });
      }
    },
    async initShop() {
      let { pubShopId, isAnonUser, pubDomainShopId } = this;
      console.log("初始化商店信息", pubShopId);
      if (!pubShopId) {
        this.pubShopId = pubDomainShopId;
      }
      if (!pubShopId) return;
      await this.getShopDetail();
      if (!isAnonUser) {
        await this.$store.dispatch("sp-store/index/initCart", pubShopId);
        await userJoinPubDomainBusinessUser({ pubDomainShopId: pubShopId });
      }
      this.showLoading = false;
    },
    // 获取商圈详情
    async getShopDetail() {
      let { pubShopId: id } = this;
      await getShopDetail({ id })
        .then((res) => {
          if (!res) {
            uni.showToast({
              icon: "none",
              title: "无法查看商圈详情~",
            });
            setTimeout(() => {
              uni.navigateBack();
            }, 1500);
            return;
          }
          this.shopInfo = res;
          let { allStatus, classifyIndustryVos } = res;
          if (classifyIndustryVos)
            this.handleSetClassification(classifyIndustryVos);
          if (allStatus === 2 || allStatus === 1) {
            uni.showModal({
              content:
                allStatus === 1
                  ? "当前商圈已打烊，请重新选择商圈下单"
                  : "当前商圈已关停，无法查看商圈详情",
              showCancel: false,
              confirmText: "我知道了",
              success: (res) => {
                if (res.confirm) {
                  this.$myTool.jumpPage("back");
                }
              },
            });
          }
        })
        .catch(() => {
          uni.showToast({
            icon: "none",
            title: "无法查看商圈详情~",
          });
          setTimeout(() => {
            uni.navigateBack();
          }, 1500);
          return;
        });
      this.getCouponList();
      this.getShopList();
      this.innitComponentsHeight();
    },
    handleSetClassification(arr) {
      let count = 0;
      arr?.map((v) => {
        v.name = `${v.classifyName}(${v.classifyCount})`;
        v.id = v.pubDomainClassifyId;
        count += v.classifyCount;
      });
      arr?.unshift({
        name: `全部(${count})`,
        id: "",
      });
      this.classification = arr;
    },
    getCouponList() {
      let { pubDomainBusinessId, id: pubDomainShopId } = this.shopInfo;
      // 获取优惠券列表
      getCoupon({
        pubDomainBusinessId,
        pubDomainShopId,
        pageSize: 999,
        pageNum: 1,
        pubTag: 1,
      }).then((res) => {
        let filter = JSON.parse(JSON.stringify(res));
        filter.length === 0 && (this.isShowCouponDown = false);
        filter.forEach((item) => {
          item.pullDown = false;
        });
        this.couponList = filter;
      });
    },
    handleChangeClassify(e) {
      let isHasChangeClassify = false;
      if (this.isFixed) {
        isHasChangeClassify = true;
      }
      this.shopList = [];
      this.getShopList(e.pubDomainClassifyId).then(() => {
        if (isHasChangeClassify) {
          uni.pageScrollTo({
            scrollTop: this.scrollHeight,
            duration: 100,
          });
        }
      });
    },
    async getShopList(pubDomainClassifyId = "") {
      let { pubDomainBusinessId } = this.shopInfo;
      let queryParams = {
        latitude: "",
        longitude: "",
        sortType: 1, // 排序规则 1综合排序 2距离优先 3人气优先
        pageNum: 1,
        pageSize: 20,
        pubDomainClassifyId,
        pubDomainBusinessId,
      };
      const res = await this.$getUserLocation();
      let result = res?.currentLocation ? res?.currentLocation : res?.location;
      let { longitude, latitude } = result;
      queryParams = Object.assign({}, queryParams, {
        longitude,
        latitude,
      });
      const classifyData = await getPubTagShopsByClassifyId({
        ...queryParams,
      });
      if (classifyData) {
        let { list = [] } = classifyData;
        if (!list) list = [];
        list.map((item) => {
          if (item.pubCoupons) {
            item.pubCoupons.map((pubCoupon) => {
              pubCoupon.pullDown = false;
            });
          }
        });
        this.shopList = list;
      }
    },
    // 领取优惠券
    pullDownCoupon(coupon) {
      if (coupon.pullDown) return;
      let { receiveCode } = coupon;
      receiveCoupon({
        receiveCode,
      })
        .then(() => {
          coupon.pullDown = true;
          uni.showToast({
            title: "领取成功",
          });
        })
        .catch((err) => {
          uni.showToast({
            title: err?.msg,
            icon: "none",
          });
        });
    },
    // 查看更多优惠券
    showCouponList() {
      this.showCoupon = true;
    },
    uGetRect(selector, all) {
      return new Promise((resolve) => {
        uni
          .createSelectorQuery()
          .in(this)
          [all ? "selectAll" : "select"](selector)
          .boundingClientRect((rect) => {
            if (all && Array.isArray(rect) && rect.length) {
              resolve(rect);
            }
            if (!all && rect) {
              resolve(rect);
            }
          })
          .exec();
      });
    },
    //获取组件高度
    async innitComponentsHeight() {
      const navBarHeight =
        this.$refs.navBar.navbarHeight + this.$refs.navBar.statusBarHeight;
      const headClass = await this.uGetRect(".head");
      const tabsClass = await this.uGetRect(".tabs");
      const headHeight = headClass.height;
      const headTop = headClass.top;
      const tabsHeight = tabsClass.height;
      const scrollHeight =
        headTop -
        navBarHeight +
        headHeight +
        tabsHeight -
        uni.$u.getPx("16rpx");
      this.scrollHeight = scrollHeight;
      this.navBarHeight = navBarHeight;
      this.tabsHeight = tabsHeight;
    },
    handlePageScrollTo(e) {
      this.isFixed = e.scrollTop >= Number(this.scrollHeight.toFixed(0));
      // console.log("滑动", this.isFixed, e.scrollTop, this.scrollHeight);
    },
  },
};
</script>
<style>
page {
  background: #f7f7f7;
  height: 100vh;
  width: 100%;
}
</style>
<style lang="scss" scoped>
$width: 710rpx;
button {
  &::after {
    display: none;
  }
}

.clearfix:after,
.clearfix:before {
  content: " ";
  display: table;
}
.clearfix:after {
  clear: both;
}
.flag {
  width: 80rpx;
  height: 32rpx;
  text-align: center;
  line-height: 30rpx;
  background: #f7f7f7;
  border: 1rpx solid #999999;
  font-size: 22rpx;
  font-weight: 500;
  border-radius: 5rpx;
  margin-right: 10rpx;
  color: #888888;
}

.open {
  background: #e2f8f0;
  border: 1rpx solid #0cd38a;
  color: #0cd38b !important;
}
.business-district-index-page {
  //height: 100vh;
  //overflow: hidden;
  //overflow-y: scroll;
  //overflow-anchor: auto;
}
.head-bg {
  width: 100%;
  height: 396rpx;
  position: absolute;
  top: 0;
  left: 0;
  z-index: -1;
}
.navLeft {
  display: flex;
  padding-left: 16rpx;
}
.tabs {
  width: 100%;
  background: #f7f7f7;
}
.transition {
  transition: all 0.1s linear;
}
.content {
  width: 100vw;
  z-index: 1;
  .container {
    width: $width;
    margin: 0 auto;
    margin-top: 300rpx;
  }
  .head {
    position: relative;
    background-color: #f7f7f7;
    border-radius: 20rpx;
    .head-content {
      background: #ffffff;
      padding: 30rpx 20rpx;
      border-radius: 20rpx;
      box-shadow: 0rpx 8rpx 20rpx 0rpx #e6e6e6;
    }
    .top {
      display: flex;
      align-items: center;
      border-bottom: 1rpx solid #ebebeb;
      padding-bottom: 28rpx;
      .top-left {
        flex: 1;
        .shopName {
          display: flex;
          align-items: center;
          font-size: 32rpx;
          font-family: PingFang SC;
          font-weight: bold;
          color: #1a1a1a;
          line-height: 36rpx;
        }
        .title {
          flex: 1;
        }
        .address {
          margin-top: 29rpx;
          font-size: 22rpx;
          font-family: PingFang SC;
          font-weight: 500;
          color: #999999;
        }
      }
      .top-right {
        display: flex;
        align-items: center;
        justify-content: center;
        .btn {
          text-align: center;
          padding: 0 27rpx;
          font-size: 22rpx;
          .title {
            margin-top: 9rpx;
            font-size: 22rpx;
            font-family: PingFang SC;
            font-weight: 500;
            color: #999999;
          }
        }
        .img-icon {
          width: 38rpx;
          height: 38rpx;
        }
        .lookLocation {
          border-right: 1rpx solid #ebebeb;
        }
      }
    }
  }
  .shop-list {
    padding: 20rpx;
    background-color: #fff;
    border-radius: 20rpx;
    margin: 16rpx auto 0 auto;
    .shop-content {
      display: flex;
      margin: 22rpx auto;
      background-color: #fff;
      border-radius: 18rpx;
      .img {
        width: 170rpx;
        height: 170rpx;
        margin-right: 20rpx;
      }

      .msg {
        flex: 1;
        width: 0;
        display: flex;
        flex-direction: column;

        // justify-content: space-between;
        .title {
          font-size: 32rpx;
          font-weight: bold;
          color: #181818;
          margin-bottom: 20rpx;
          white-space: nowrap;
          text-overflow: ellipsis;
          overflow: hidden;
        }

        .detail {
          display: flex;
          align-items: center;
          font-size: 27rpx;
          font-weight: 500;
          color: #888888;
          justify-content: space-between;

          .left {
            display: flex;
            align-items: center;

            .type {
              padding-right: 15rpx;
              margin-right: 15rpx;
              position: relative;

              &::after {
                content: "";
                width: 1px;
                height: 27rpx;
                background-color: #ddd;
                position: absolute;
                right: 0;
                top: 50%;
                transform: translateY(-50%);
              }
            }
          }
        }

        .store-val {
          font-size: 29rpx;
          font-weight: 500;
          // color: #fff;
          margin-top: auto;
          .ticket {
            display: flex;
            align-items: center;
            justify-content: space-between;
            width: calc(100%);
            margin: 0 auto;
            margin-top: 24rpx;
            font-family: PingFang SC;
            .ticket_list {
              flex: 1;
              overflow: hidden;
              white-space: nowrap;
            }
          }
        }
      }
    }
  }
  .empty {
    margin-top: 50%;
  }
}

.ticket_item {
  font-size: 16rpx;
  font-family: PingFang SC;
  font-weight: 500;
  background-color: #fff5f0;
  position: relative;
  z-index: 5;
  align-items: center;
  height: 50rpx;
  color: #daa629;
  border: 1rpx solid #daa629;
  padding: 0 9rpx 0 4rpx;
  overflow: hidden;
  margin-right: 20rpx;
  border-radius: 6rpx;
  display: inline-flex;

  .discount {
    font-size: 20rpx;
    font-family: PingFang SC;
    color: #daa629;
    border-right: 1px dashed #daa629;
    padding-right: 9rpx;
    display: inline-flex;
    align-items: baseline;
    .discount-unit {
      font-size: 16rpx;
      color: var(--theme-color);
      padding: 1rpx;
    }
    .discount-content {
      font-size: 20rpx;
      font-weight: 500;
      color: var(--theme-color);
    }
  }

  .rule {
    display: inline-block;
    position: relative;
    margin-right: 15rpx;
    font-size: 16rpx;
    padding-left: 8rpx;
  }

  .get {
    width: 34rpx;
    height: 34rpx;
    background: var(--theme-color);
    font-size: 16rpx;
    font-family: PingFang SC;
    font-weight: 500;
    color: #ffffff;
    border-radius: 6rpx;
    align-items: center;
    display: flex;
    justify-content: center;
    &.took {
      background: transparent;
      border-left: 1rpx solid var(--theme-color);
      color: var(--theme-color);
      border-radius: 0;
      padding-left: 5rpx;
    }
  }
}
.see_all {
  white-space: nowrap;
  font-size: 26rpx;
  font-family: PingFang SC;
  font-weight: 500;
  color: #999999;
  display: flex;
  align-items: center;
  margin-left: 13rpx;
  //color: var(--theme-color);
}
.ticket {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: calc(100%);
  margin: 24rpx auto 0;
  .ticket_list {
    flex: 1;
    overflow: hidden;
    white-space: nowrap;
  }
}

.no_touch {
  width: 100vw;
  height: 100vh;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 99999;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  font-size: 29rpx;
  color: #fff;

  .icon {
    margin-bottom: 20rpx;
  }

  .content {
    width: 200rpx;
    height: 200rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    background-color: #181818;
    border-radius: 15rpx;
  }
}
</style>
